<template>
  <div class="admin-edit-pet">
    <div class="container">
      <div class="back-link mb-3">
        <a href="/admin/pets">
          <i class="el-icon-arrow-left"></i> 返回宠物列表
        </a>
      </div>
      
      <h1 class="page-title">编辑宠物</h1>
      
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="10" animated />
      </div>
      
      <template v-else-if="!petData">
        <el-empty description="未找到宠物信息"></el-empty>
      </template>
      
      <el-card v-else class="pet-form-card">
        <el-form 
          ref="petForm" 
          :model="petData" 
          :rules="rules" 
          label-position="top"
          @submit.prevent="directSave"
        >
          <el-row :gutter="20">
            <el-col :md="12" :sm="24">
              <el-form-item label="宠物名称" prop="name">
                <el-input v-model="petData.name" placeholder="请输入宠物名称" />
              </el-form-item>
            </el-col>
            
            <el-col :md="12" :sm="24">
              <el-form-item label="类别" prop="category_id">
                <el-select v-model="petData.category_id" placeholder="请选择宠物类别" style="width: 100%">
                  <el-option 
                    v-for="category in categories" 
                    :key="category.id" 
                    :label="category.name" 
                    :value="category.id" 
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :md="6" :sm="12" :xs="24">
              <el-form-item label="性别" prop="gender">
                <el-select v-model="petData.gender" placeholder="请选择性别" style="width: 100%">
                  <el-option label="公" value="male" />
                  <el-option label="母" value="female" />
                  <el-option label="未知" value="unknown" />
                </el-select>
              </el-form-item>
            </el-col>
            
            <el-col :md="6" :sm="12" :xs="24">
              <el-form-item label="年龄" prop="age">
                <el-input-number v-model="petData.age" :min="0" :max="30" style="width: 100%" />
              </el-form-item>
            </el-col>
            
            <el-col :md="6" :sm="12" :xs="24">
              <el-form-item label="品种" prop="breed">
                <el-input v-model="petData.breed" placeholder="请输入品种" />
              </el-form-item>
            </el-col>
            
            <el-col :md="6" :sm="12" :xs="24">
              <el-form-item label="体型" prop="size">
                <el-select v-model="petData.size" placeholder="请选择体型" style="width: 100%">
                  <el-option label="小型" value="small" />
                  <el-option label="中型" value="medium" />
                  <el-option label="大型" value="large" />
                  <el-option label="超大型" value="extra large" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="宠物状态" prop="is_adopted">
                <el-select v-model="petData.is_adopted" placeholder="请选择宠物状态" style="width: 100%">
                  <el-option label="未领养" :value="0" />
                  <el-option label="已领养" :value="1" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-form-item label="健康状况" prop="health_status">
            <el-input 
              type="textarea" 
              v-model="petData.health_status" 
              placeholder="请输入宠物的健康状况" 
              :rows="3" 
            />
          </el-form-item>
          
          <el-form-item label="行为习性" prop="behavior">
            <el-input 
              type="textarea" 
              v-model="petData.behavior" 
              placeholder="请输入宠物的行为习性" 
              :rows="3" 
            />
          </el-form-item>
          
          <el-form-item label="宠物介绍" prop="description">
            <el-input 
              type="textarea" 
              v-model="petData.description" 
              placeholder="请输入宠物的详细介绍" 
              :rows="5" 
            />
          </el-form-item>
          
          <el-form-item label="宠物照片">
            <el-upload
              class="pet-image-uploader"
              action="#"
              :http-request="uploadImage"
              :show-file-list="false"
              :before-upload="beforeImageUpload"
            >
              <img v-if="imageUrl" :src="imageUrl" class="pet-image" />
              <i v-else class="el-icon-plus pet-image-uploader-icon"></i>
              <div class="el-upload__tip">点击更换宠物照片，只能上传 jpg/png 文件，且不超过 5MB</div>
            </el-upload>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="directSave" :loading="submitting">
              {{ submitting ? '保存中...' : '保存修改' }}
            </el-button>
            <el-button @click="goBackToList">取消</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useStore } from 'vuex';
import axios from 'axios';

export default {
  name: 'AdminEditPet',
  props: {
    id: {
      type: String,
      required: true
    }
  },
  setup(props) {
    console.log('EditPet组件开始初始化，传入的宠物ID:', props.id);
    
    const store = useStore();
    const router = useRouter();
    const petForm = ref(null);
    const loading = ref(true);
    const submitting = ref(false);
    const imageUrl = ref('');
    const imageFile = ref(null);
    const petData = ref(null);
    
    const API_URL = process.env.VUE_APP_API_URL || 'http://localhost:3000/api';
    
    // 分类数据
    const categories = ref([]);
    
    // 表单验证规则
    const rules = {
      name: [
        { required: true, message: '请输入宠物名称', trigger: 'blur' },
        { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
      ],
      category_id: [
        { required: true, message: '请选择宠物类别', trigger: 'change' }
      ],
      gender: [
        { required: true, message: '请选择性别', trigger: 'change' }
      ],
      size: [
        { required: true, message: '请选择体型', trigger: 'change' }
      ],
      is_adopted: [
        { required: true, message: '请选择宠物状态', trigger: 'change' }
      ]
    };
    
    // 获取认证头
    const authHeader = computed(() => ({
      headers: {
        'Authorization': `Bearer ${store.getters['auth/token']}`
      }
    }));
    
    // 加载宠物数据
    const loadPet = async () => {
      loading.value = true;
      try {
        const response = await axios.get(`${API_URL}/pets/${props.id}`);
        
        // 设置宠物数据
        const data = response.data;
        console.log('原始宠物数据:', data);
        
        // 确保数据类型正确
        if (data.category_id !== undefined) {
          data.category_id = Number(data.category_id);
        }
        
        // 确保is_adopted有正确的值
        if (typeof data.is_adopted === 'string') {
          data.is_adopted = Number(data.is_adopted);
        }
        if (data.is_adopted === undefined) {
          data.is_adopted = 0;
        }
        
        // 为空值设置默认值
        if (data.health_status === null) data.health_status = '';
        if (data.behavior === null) data.behavior = '';
        if (data.description === null) data.description = '';
        
        petData.value = data;
        
        // 设置图片URL
        if (petData.value.image_url) {
          imageUrl.value = `${API_URL.replace('/api', '')}${petData.value.image_url}`;
        }
        
        console.log('处理后的宠物数据:', petData.value);
      } catch (error) {
        ElMessage.error('加载宠物数据失败');
        console.error('加载宠物数据错误:', error);
      } finally {
        loading.value = false;
      }
    };
    
    // 加载分类数据
    const loadCategories = async () => {
      try {
        const response = await axios.get(`${API_URL}/pets/categories`);
        if (Array.isArray(response.data)) {
          categories.value = response.data.map(cat => ({
            ...cat,
            id: Number(cat.id)
          }));
          console.log('加载的分类数据:', categories.value);
        } else {
          console.error('分类数据格式不正确:', response.data);
          categories.value = [];
        }
      } catch (error) {
        console.error('加载分类数据错误:', error);
      }
    };
    
    // 图片上传前的验证
    const beforeImageUpload = (file) => {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isLt5M = file.size / 1024 / 1024 < 5;
      
      if (!isJPG && !isPNG) {
        ElMessage.error('上传头像图片只能是 JPG 或 PNG 格式!');
        return false;
      }
      
      if (!isLt5M) {
        ElMessage.error('上传头像图片大小不能超过 5MB!');
        return false;
      }
      
      imageFile.value = file;
      return true;
    };
    
    // 自定义上传图片方法
    const uploadImage = (options) => {
      const file = options.file;
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => {
        imageUrl.value = reader.result;
      };
    };
    
    // 直接保存方法，简化逻辑
    const directSave = async () => {
      console.log('直接保存方法被调用');
      
      if (!petForm.value) {
        console.error('表单引用不存在');
        ElMessage.error('表单引用不存在，请刷新页面重试');
        return;
      }
      
      // 先进行表单验证
      petForm.value.validate(async (valid) => {
        if (!valid) {
          ElMessage.warning('请正确填写表单');
          return;
        }
        
        submitting.value = true;
        
        try {
          // 创建表单数据
          const formData = new FormData();
          
          // 如果有上传新图片，则添加到表单
          if (imageFile.value) {
            formData.append('image', imageFile.value);
          }
          
          // 添加所有字段到表单数据
          formData.append('name', petData.value.name);
          formData.append('breed', petData.value.breed || '');
          formData.append('gender', petData.value.gender || 'unknown');
          formData.append('age', petData.value.age || 0);
          formData.append('size', petData.value.size || 'medium');
          formData.append('is_adopted', petData.value.is_adopted);
          formData.append('description', petData.value.description || '');
          formData.append('health_status', petData.value.health_status || '');
          formData.append('behavior', petData.value.behavior || '');
          formData.append('category_id', Number(petData.value.category_id));
          
          console.log('准备提交表单数据');
          
          // 发送请求
          const response = await axios.put(
            `${API_URL}/pets/${props.id}`, 
            formData,
            {
              headers: {
                'Content-Type': 'multipart/form-data'
              }
            }
          );
          
          console.log('更新宠物响应:', response);
          
          // 成功提示
          ElMessage.success('宠物信息更新成功');
          
          // 使用延时确保消息显示
          setTimeout(() => {
            window.location.href = '/admin/pets';
          }, 1000);
        } catch (error) {
          console.error('保存错误:', error);
          ElMessage.error('保存失败，请检查控制台错误信息');
        } finally {
          submitting.value = false;
        }
      });
    };
    
    // 返回列表页面
    const goBackToList = () => {
      console.log('返回列表页面');
      window.location.href = '/admin/pets';
    };
    
    // 组件挂载时加载数据
    onMounted(async () => {
      console.log('EditPet组件已挂载，开始加载数据');
      try {
        await Promise.all([loadPet(), loadCategories()]);
        console.log('数据加载完成，petForm引用状态:', !!petForm.value);
      } catch (error) {
        console.error('组件初始化错误:', error);
      }
    });
    
    return {
      petForm,
      petData,
      categories,
      rules,
      loading,
      submitting,
      imageUrl,
      imageFile,
      beforeImageUpload,
      uploadImage,
      directSave,
      goBackToList
    };
  }
}
</script>

<style lang="scss" scoped>
@use "sass:color";

.admin-edit-pet {
  min-height: calc(100vh - 200px);
  padding: 40px 0;
}

.loading-container {
  min-height: 400px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.back-link {
  margin-bottom: 20px;
  
  a {
    color: var(--primary-color);
    display: inline-flex;
    align-items: center;
    
    i {
      margin-right: 5px;
    }
    
    &:hover {
      color: color.adjust(#42b983, $lightness: -10%);
    }
  }
}

.pet-form-card {
  margin-bottom: 40px;
}

.pet-image-uploader {
  :deep(.el-upload) {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: all 0.3s;
    
    &:hover {
      border-color: var(--primary-color);
    }
  }
  
  .pet-image-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 200px;
    height: 200px;
    line-height: 200px;
    text-align: center;
  }
  
  .pet-image {
    width: 200px;
    height: 200px;
    display: block;
    object-fit: cover;
  }
}

.mb-3 {
  margin-bottom: 15px;
}

@media (max-width: 768px) {
  .pet-image-uploader {
    .pet-image-uploader-icon,
    .pet-image {
      width: 100%;
    }
  }
}
</style> 